package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.LikesService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LikesServiceImpl implements LikesService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult likes(LikesBehaviorDto dto) {
        //1.校验
        if(dto==null || dto.getArticleId()==null || dto.getOperation()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //点赞必须得登陆
        // 前提条件是
        // 1.网关解析令牌得到用户id放入请求头然后路由到behavior微服务
        // 2.behaviro服务中要有拦截器  在前置拦截方法中获取请求头中的用户id  放入threadlocal，  拦截器需要生效
        WmUser user = WmThreadLocalUtil.getUser();
        if(user==null || user.getId()==0){// 没登陆  或者点了不登录先看看   都不允许点点赞按钮
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.利用redis的set结构存储点赞信息
        String userId = user.getId().toString();//当前登录人id
        String articleId = dto.getArticleId().toString();//点赞的文章的id

        //存储该文章的  点赞用户  id集合            LIKE-BEHAVIOR-1383827888816836609:  [1001]
        BoundSetOperations<String, String> setOps = stringRedisTemplate.boundSetOps(BehaviorConstants.LIKE_BEHAVIOR + articleId);



        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());//文章id
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);//行为操作  LIKES是点赞行为
        if(dto.getOperation()==0){//点赞
            Boolean member = setOps.isMember(userId);
            if(member!=null && member){
                //点赞时  之前已经点过赞了
                return ResponseResult.errorResult(AppHttpCodeEnum.LIKE_EXISTS);
            }
            setOps.add(userId);//如果没有点过赞，则存储该用户id
            mess.setAdd(1);//点赞
        }else{//取消赞
            Boolean member = setOps.isMember(userId);
            if(member!=null && !member){
                //说明取消赞时，之前都没点赞
                return ResponseResult.errorResult(AppHttpCodeEnum.LIKE_NOT_EXISTS);
            }
            setOps.remove(userId);
            mess.setAdd(-1);//取消赞
        }
        //发送消息到kafka
        log.info("behavior发送行为消息: {}", JSON.toJSONString(mess));
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

        //3.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
